<template>
  <!-- 部门管理 -->
  <div>
    <div class="app-container">
      <div class="form-container">
        <el-form
          ref="filters"
          :inline="true"
          label-width="80px"
          :model="filters"
        >
          <el-form-item label="部门名称" prop="deptName">
            <el-input
              v-model="filters.deptName"
              size="small"
              placeholder="部门名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="部门类型" prop="deptType">
            <el-select v-model="filters.deptType" clearable size="small">
              <el-option
                v-for="dict in deptAndSubCompanyTypeOptions "
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门状态" prop="status">
            <el-select
              v-model="filters.status"
              size="small"
              clearable
              placeholder="请选择"
              prop="status"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :clearable="false"
            />
          </el-form-item>
          <!-- 高级设置一栏 start -->
          <!-- <el-form-item>
            <slot name="label">
              <i class="highLevelStyle" :class="highLevelSet===true?'el-icon-arrow-up':'el-icon-arrow-down'" @click="highLevelSet = !highLevelSet" />
            </slot>
          </el-form-item> -->

        </el-form>
      </div>
      <div class="btns-group">
        <systemBtns :single="isAmend" has-permi="dept" />
        <el-button v-hasPermi="[ 'system:dept:init']" size="middle" icon="el-icon-s-home" :disabled="isInitialize" @click="initEntAdd()">详情</el-button>
        <el-button v-hasPermi="['system:subCompany:resetPwd']" icon="el-icon-refresh" size="middle" :disabled="isInitialize" @click="passwordReset()">分公司密码重置</el-button>
        <el-button v-show="status === '1'" v-hasPermi="['system:dept:edit']" size="middle" icon="el-icon-star-on" :disabled="isAmend" @click="handleStatusChange">启用</el-button>
        <el-button v-show="status === '0'" v-hasPermi="['system:dept:edit']" size="middle" icon="el-icon-star-off" :disabled="isAmend" @click="handleStatusChange">停用</el-button>
      </div>
      <!-- 树形表格展示start -->
      <div ref="table">
        <el-table
          ref="multipleTable"
          v-loading="tableLoading"
          :data="daptTreeDate"
          stripe
          class="table-list"
          row-key="deptId"
          :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height-tree' : 'el-body-page-roll-height-tree') :
            (needTagsView===true ? 'el-body-page-roll-tag-tree' : 'el-body-page-roll-tree')"
          :default-expand-all="true"
          :row-style="rowClass"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          @select-all="handleSelectionChange"
          @selection-change="selectionChange"
          @row-click="rowChecked"
        >
          <el-table-column type="selection" width="38" />
          <el-table-column prop="deptName" min-width="200px" header-align="center" label="部门名称" />
          <el-table-column prop="deptType" min-width="100px" :formatter="(row) => deptTypeFormatter(row.deptType)" align="center" label="部门类型" />
          <el-table-column prop="orderNum" min-width="50px" align="center" label="排序" />
          <el-table-column prop="status" min-width="60px" align="center" label="状态">
            <template slot-scope="scope" :formatter="statusFormat">
              <span v-if="scope.row.status=== '0'">正常</span>
              <span v-if="scope.row.status=== '1'">停用</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="createTime" align="center" label="创建时间" /> -->
        </el-table>
      </div>
      <!-- 树形表格展示end-->

      <!-- 添加页面end-->
      <!-- 初始化页面 -->
      <init-add v-if="addVisible" ref="initAdd" />
      <!-- 初始化查看页面 -->
      <init-detail v-if="detailVisible" ref="initDetail" />
    </div>
    <!-- 添加页面start -->
    <!-- v-dialogDrag -->
    <el-dialog
      :title="dialogTitle"
      style="padding: 0px;"
      top="8vh"
      :visible.sync="dialogVisible"
      :before-close="cancel"
      class="dialogStyleMiddle"
      :close-on-click-modal="false"
    >
      <el-form ref="addSysDeptForm" :model="sysDept" :rules="rules" label-width="95px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect
                v-model="sysDept.parentId"
                size="medium"
                :options="deptOptions"
                placeholder="请选择上级部门"
                :disabled="isParentIdDisabled"
                no-options-text="暂无数据"
                :clearable="false"
                clear-value-text=""
                @select="selectParentId"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父部门编码" prop="parentCode">
              <el-input v-model="sysDept.parentCode" placeholder="请输入父部门编码" disabled size="medium" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="sysDept.deptName" placeholder="请输入部门名称" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本部门编码" prop="deptCode">
              <el-input v-model="sysDept.deptCode" placeholder="请输入部门编码" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门类型" prop="deptType">
              <el-select v-model="sysDept.deptType" style="width:100%" size="medium" :disabled="editReadOnly" @change="handleChange">
                <el-option
                  v-for="dict in deptSubCompanyTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                  size="medium"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number v-model.number="sysDept.orderNum" controls-position="right" size="medium" :min="1" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="sysDept.deptType !== '2'" label="负责人员" prop="leader">
              <el-input v-model="sysDept.leader" placeholder="请输入负责人" size="medium" />
            </el-form-item>
          </el-col>
          <el-col v-if="sysDept.deptType === '2' && getEnterpriseType() === '1'" :span="12">
            <el-form-item prop="province" label="受理范围">
              <el-cascader v-model="currentProvince" size="medium" placeholder="请选择受理范围" :props="cityNormalizer" :options="cityList" clearable style="width: 100%" @change="changeCitySelect">
                <template slot-scope="{ data }">
                  <span>{{ data.label }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col v-if="sysDept.deptType === '2' && dialogTitle !== '修改部门信息'" :span="12">
            <el-form-item label="套餐选择" prop="tempId">
              <el-select v-model="sysDept.tempId" style="width:100%" size="medium">
                <el-option
                  v-for="(item,key) in templateOptiom"
                  :key="key"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="sysDept.phone" placeholder="请填写联系电话" size="medium" @input="changePhone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="sysDept.email" placeholder="请输入邮箱" size="medium" />
            </el-form-item>
          </el-col>
          <el-col v-if="(dialogTitle !== '修改部门信息')" :span="12">
            <el-form-item v-if="sysDept.deptType === '2'" key="1" label="账号" prop="loginName">
              <label slot="label" v-html="`账&emsp;&emsp;号`" />
              <el-input v-model="sysDept.loginName" placeholder="请输入管理员账号" size="medium" :readonly="editReadOnly" />
            </el-form-item>
            <el-form-item v-else key="2" label="账号" prop="">
              <label slot="label" v-html="`账&emsp;&emsp;号`" />
              <el-input v-model="sysDept.loginName" placeholder="请输入管理员账号" size="medium" :readonly="editReadOnly" />
            </el-form-item>
          </el-col>
          <el-col v-if="(dialogTitle !== '修改部门信息')" :span="12">
            <el-form-item v-if="sysDept.deptType === '2'" key="1" label="姓名" prop="userName">
              <label slot="label" v-html="`姓&emsp;&emsp;名`" />
              <el-input v-model="sysDept.userName" size="medium" placeholder="请输入管理员姓名" :readonly="editReadOnly" />
            </el-form-item>
            <el-form-item v-else key="2" label="姓名" prop="">
              <label slot="label" v-html="`姓&emsp;&emsp;名`" />
              <el-input v-model="sysDept.userName" size="medium" placeholder="请输入管理员姓名" :readonly="editReadOnly" />
            </el-form-item>
          </el-col>
          <el-col v-if="editShow && (dialogTitle !== '修改部门信息')" :span="12">
            <el-form-item v-if="sysDept.deptType === '2'" key="1" label="密码" prop="password">
              <label slot="label" v-html="`密&emsp;&emsp;码`" />
              <el-input
                v-model="sysDept.password"
                placeholder="请输入密码"
                type="password"
                size="medium"
              />
            </el-form-item>
            <el-form-item v-else key="2" label="密码" prop="">
              <label slot="label" v-html="`密&emsp;&emsp;码`" />
              <el-input
                v-model="sysDept.password"
                placeholder="请输入密码"
                type="password"
                size="medium"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="editShow && (dialogTitle !== '修改部门信息')" :span="12">
            <el-form-item v-if="sysDept.deptType === '2'" key="1" label="确认密码" prop="confirmPassword">
              <el-input
                v-model="sysDept.confirmPassword"
                placeholder="请输入密码"
                type="password"
                size="medium"
              />
            </el-form-item>
            <el-form-item v-else key="2" label="确认密码" prop="">
              <el-input
                v-model="sysDept.confirmPassword"
                placeholder="请输入密码"
                type="password"
                size="medium"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="cancel">取 消</el-button>
        <el-button v-clickForbidden type="primary" size="medium" @click="submitForm('addSysDeptForm')">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEnterpriseType } from '@/utils/auth'
import { listRegionTree } from '@/api/common/area.js'
// 企业套餐list方法
import { getCompTemp } from '@/api/system/dept'
// import { Message } from 'element-ui'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import InitAdd from './components/DeptInitAdd'
import InitDetail from './components/DeptInitDetail'
// 引入高级设置一栏
// import HighLevelSetting from '@/components/HighLevelSetting'
// 按钮组件
import systemBtns from '@/components/Common/Btns/systemBtns'
import {
  listDept,
  getDeptByDeptId,
  addDept,
  updateDept,
  delDept,
  seleteDeptTree,
  checkDeptNameUnique,
  getDeptCodeByParentCode,
  resetPswdSubCompany,
  initialized
} from '@/api/system/dept'
import { checkPhoneUnique } from '@/api/system/user'
import { mapState } from 'vuex'
export default {
  components: { Treeselect, InitAdd, InitDetail, systemBtns },
  data() {
    var checkLoginName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('登录账号不能为空'))
      } else if (value.length < 2) {
        return callback(new Error('登录账号长度不能小于2位'))
      } else if (value.length > 20) {
        return callback(new Error('登录账号长度不能大于20位'))
      } else {
        // var userId = ''
        // var loginName = value
        // checkLoginNameUnique(userId, loginName).then(res => {
        //   if (res.code !== 0) {
        //     return callback(new Error('登录名称已经存在'))
        //   } else {
        //     }
        callback()
      }
    }
    var validUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名称不能为空'))
      } else if (value.length < 2) {
        return callback(new Error('用户名称长度不能小于2位'))
      } else if (value.length > 20) {
        return callback(new Error('用户名称长度不能大于20位'))
      } else {
        callback()
      }
    }
    var validPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'))
      } else if (value.length < 6) {
        return callback(new Error('密码长度不能小于6位'))
      } else if (value.length > 20) {
        return callback(new Error('密码长度不能大于20位'))
      } else {
        callback()
      }
    }
    var checkConfirmPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('确认密码不能为空'))
      } else if (value !== this.sysDept.password) {
        return callback(new Error('确认密码与登录密码不一致'))
      } else {
        callback()
      }
    }
    var checkDeptName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空'))
      } else {
        var parentId = this.sysDept.parentId
        var deptId = this.sysDept.deptId
        var deptName = value
        checkDeptNameUnique(parentId, deptId, deptName).then(response => {
          if (response.data === '1') {
            return callback(new Error('该部门名称已经存在'))
          } else {
            callback()
          }
        })
      }
    }
    // 电话号码查重验证
    const validatePhone = (rule, value, callback) => {
      const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (value === '' || value === undefined || value === null) {
        callback()
      } else {
        if ((!reg.test(value)) && value !== '') {
          callback(new Error('请输入正确的电话号码'))
        } else {
          const phone = value
          checkPhoneUnique('', phone).then(resp => {
            if (resp.data === '1') {
              return callback(new Error('该手机已被注册，请重新输入！'))
            } else {
              callback()
            }
          })
        }
      }
    }
    /* const validPhoneNumber = (rule, value, callback) => {
      if (value) {
        const phone = value
        checkPhoneUnique('', phone).then(resp => {
          if (resp.data === '1') {
            return callback(new Error('该手机已被注册，请重新输入！'))
          } else {
            callback()
          }
        })
      }
    }*/
    return {
      getEnterpriseType,
      cityNormalizer: {
        value: 'value',
        label: 'label',
        children: 'children'
      },
      // 三级城市列表
      cityList: [],
      // 上级部门是否禁用
      isParentIdDisabled: false,
      // 最大部门编码
      maxDeptCode: '',
      status: '0',
      // 高级设置显示隐藏
      highLevelSet: false,
      // 高亮数组
      selectRow: [],
      // 高亮子数组
      rowTableData: [],
      // 高级设置参数
      highLevelSettingData: [
        {
          label: '创建时间',
          isDatePicker: 1,
          size: 'small',
          type: 'daterange',
          separator: '-',
          start: '开始日期',
          end: '结束日期',
          isClearable: false,
          prop: 'createTime',
          model: []
        }
      ],
      // 模板名称
      templateOptiom: [],
      // 修改按钮是否可用
      isAmend: true,
      // 删除按钮是否可用
      isInitialize: true,
      isLookInitialize: true,
      // 管理员信息修改时只读
      editReadOnly: false,
      // 密码框是否显示
      editShow: true,
      // 搜索框
      filters: {
        // 部门名称
        deptName: '',
        // 状态
        status: '0',
        // 部门类型
        deptType: '',
        // 负责人员
        leader: '',
        // 联系电话
        phone: '',
        dataObjType: 'SysDept'
      },
      // 时间范围数组
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 选中表格对话框的存储的值
      multipleSelection: [],
      daptTreeDate: [],
      tableData: [],
      // 数据总条数
      total: 0,
      // 弹出的对话框的标题
      dialogTitle: '',
      // 对话框是否弹出显示
      dialogVisible: false,
      // 表格加载是否显示等待图标
      tableLoading: false,
      //   初始化弹框
      addVisible: false,
      // 初始化查看弹框
      detailVisible: false,
      sysDept: {
        deptId: '',
        enterpriseId: '',
        parentCode: '',
        deptCode: '',
        deptType: '',
        parentId: 'undefined',
        deptName: '',
        orderNum: '',
        leader: '',
        phone: '',
        email: '',
        status: '0',
        // 管理员账号
        loginName: '',
        // 管理员用户名
        userName: '',
        // 密码
        password: '',
        tempId: '',
        province: ''
      },
      currentProvince: [],
      currentRow: null,
      // 部门树选项
      deptOptions: [],
      rowDeptOptions: [],
      // 部门类型 1:公司部门 2:分公司,3:分公司部门(分公司下选择)
      deptTypeOptions: [],
      deptSubCompanyTypeOptions: [],
      // 分公司类型
      subCompanyTypeOptions: [],
      deptAndSubCompanyTypeOptions: [],
      // 保存按钮禁用
      btnDisabled: false,
      rules: {
        province: [{ required: true, message: '受理范围不能为空', trigger: 'change' }],
        tempId: [{ required: true, message: '分公司套餐不能为空', trigger: 'blur' }],
        deptCode: [
          { required: true, message: '部门编码必填', trigger: 'blur' }
        ],
        deptName: [
          { required: true, validator: checkDeptName, trigger: 'blur' }
        ],
        leader: [{ required: true, message: '必填', trigger: 'blur' }],
        orderNum: [
          { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
        ],
        deptType: [
          { required: true, message: '部门类型不能为空', trigger: 'blur' }
        ],
        // email: [
        //   {
        //     type: 'email',
        //     required: true,
        //     message: '请输入正确的邮箱地址',
        //     trigger: ['blur']
        //   }
        // ],
        phone: [
          /* {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            required: false,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          },*/
          { required: false, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        loginName: [{ required: true, validator: checkLoginName, trigger: 'blur' }],
        userName: [{ required: true, validator: validUserName, trigger: 'blur' }],
        password: [{ required: true, validator: validPassword, trigger: 'blur' }],
        confirmPassword: [
          { required: true, validator: checkConfirmPassword, trigger: 'blur' }
        ]
      },
      maxOrderNum: 1,
      maxNum: 1
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    }
  },
  created() {
    // 部门状态
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data.rows
    })
    // 部门类型
    this.getDicts('sys_dept_deptType').then(response => {
      this.deptTypeOptions = response.data.rows
      this.deptSubCompanyTypeOptions = response.data.rows
      this.deptAndSubCompanyTypeOptions = [{ dictValue: '', dictLabel: '全部' }]
      if (this.subCompanyTypeOptions.length > 0) {
        this.deptAndSubCompanyTypeOptions = this.deptTypeOptions.concat(this.subCompanyTypeOptions)
      }
    })
    // 分公司类型
    this.getDicts('sys_dept_subCompanyType').then(response => {
      this.subCompanyTypeOptions = response.data.rows
      this.deptAndSubCompanyTypeOptions = []
      if (this.deptTypeOptions.length > 0) {
        this.deptAndSubCompanyTypeOptions = this.deptTypeOptions.concat(this.subCompanyTypeOptions)
      }
    })
    this.$nextTick(() => {
      this.getDeptTree()
    })
  },
  mounted() {
    this.getList()
    const _this = this// 赋值vue的this
    window.onresize = () => {
      // 调用methods中的事件
      // _this.AddTaleData(_this.tableData, _this.total)
    }
    // 跳转路由时关闭窗口提交
    this.$once('hook:beforeDestroy', () => {
      window.onresize = null
    })
    this.getComTempList()
    this.getCityList()
  },
  methods: {
    // 监听手机号变化
    changePhone(e) {
      console.log(e)
    },
    // 翻译部门类型
    deptTypeFormatter(deptType) {
      switch (deptType) {
        case '0':
          return '总公司'
        case '1':
          return '公司部门'
        case '2':
          return '分公司'
        case '3':
          return '分公司部门'
      }
    },
    // 清空负责人
    handleChange(type) {
      if (type === '1') {
        this.sysDept.tempId = ''
        this.currentProvince = []
      } else if (type === '2') {
        this.sysDept.leader = ''
      }
    },
    // 所属区域
    changeCitySelect(regionCode) {
      const [province, city, county] = regionCode
      this.sysDept.province = province // 省
      this.sysDept.city = city// 市
      this.sysDept.county = county // 区/县
    },
    getCityList() {
      listRegionTree().then(res => {
        if (res.data) {
          this.cityList = res.data
        }
      })
    },
    // 获取企业套餐
    getComTempList(enterpriseId, subCompany) {
      getCompTemp({ enterpriseId: enterpriseId, subCompany: subCompany }).then(resp => {
        if (resp) {
          this.templateOptiom = resp.data.rows
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 部门状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 部门类型字典翻译
    deptTypeFormat(row, column) {
      return this.selectDictLabel(this.deptTypeOptions, row.deptType)
    },
    // 单击每行时每行的复选框选中
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach(item => {	// 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    // 选择表格前面的对话框时触发的方法
    handleSelectionChange(selection) {
      if (this.multipleSelection.length === 1) {
        this.status = this.multipleSelection[0].status
      }
      if (selection.length === this.daptTreeDate.length) {
        for (let i = 0; i < selection.length; i++) {
          if (selection[i].children) {
            for (let j = 0; j < selection[i].children.length; j++) {
              this.$refs.multipleTable.toggleRowSelection(selection[i].children[j])
            }
          }
        }
      } else {
        for (let j = selection.length - 1; j >= 0; j--) {
          this.$refs.multipleTable.toggleRowSelection(selection[j])
        }
      }
    },
    selectionChange(selection) {
      if (selection[0] !== undefined) {
        if (!('deptId' in selection[0]) || selection[0].deptId === '' || selection[0].deptId === undefined || selection[0].deptId === null) {
          selection = []
          this.$refs.multipleTable.clearSelection()
        }
      }
      this.multipleSelection = selection
      this.isAmend = selection.length !== 1
      if (selection.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(selection.pop())
      }
      if (selection.length === 1) {
        this.status = selection[0].status
        if (selection[0].deptType === '2') {
          this.isInitialize = false
        } else {
          this.isInitialize = true
        }
      } else {
        this.status = '0'
        this.isInitialize = true
      }
      this.selectRow = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.rowTableData.indexOf(item))
        })
      }
    },
    getList() {
      this.tableLoading = true
      listDept(this.changeDateRange(this.filters, this.dateRange)).then(resp => {
        // _this.daptTreeDate = resp.data
        if (resp) {
          this.daptTreeDate = resp.data
          this.tableData = resp.data
          this.rowTableData = []
          this.getTableData(this.daptTreeDate)
          // this.total = resp.total
          if (resp.data === null) {
            this.total = 0
          } else {
            this.total = resp.data.length
          }
          // this.AddTaleData(this.daptTreeDate, this.total)
          this.tableLoading = false
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 空白行添加
    AddTaleData(arr, num) {
      const tableHeight = this.$refs.table.offsetHeight
      const row = Math.floor(
        (tableHeight - 36) / 36 // 表格：表头/行高：36px
      )
      for (let i = 0; i < (row - num); i++) {
        this.daptTreeDate.push({})
      }
    },
    // 选择表格前面的对话框时触发的方法
    getTableData(obj) {
      for (var i in obj) {
        this.rowTableData.push(obj[i])
        if (obj[i].children) {
          this.getTableData(obj[i].children)
        }
      }
    },
    // 搜索方法
    handleQuery() {
      this.getList()
      // 将高级设置所要查询的字段放到查询参数的对象中，key值自定义，与后台配合
      // 高级设置组件显示则查询，不显示则清空高级设置中添加的查询字段
      // if (this.highLevelSet === true) {
      //   if (this.highLevelQueryParams[0].model !== '') {
      //     this.dateRange = this.highLevelQueryParams[0].model
      //   }
      // } else {
      //   this.dateRange = []
      // }
    },
    // 重置
    resetQuery() {
      this.resetForm('filters')
      this.dateRange = []
      this.highLevelSettingData[0].model = []
      this.handleQuery()
    },
    // 表单重置
    emptySysDept() {
      this.currentProvince = []
      this.sysDept = {
        deptId: '',
        enterpriseId: '',
        parentCode: '',
        deptCode: '',
        deptType: '',
        parentId: undefined,
        deptName: '',
        orderNum: '',
        leader: '',
        phone: '',
        email: '',
        status: '0',
        // 管理员账号
        loginName: '',
        // 管理员用户名
        userName: '',
        // 密码
        password: '',
        province: '',
        city: '',
        county: ''
      }
    },
    // 部门选择树列表
    getDeptTree() {
      var _this = this
      seleteDeptTree().then(resp => {
        if (resp) {
          _this.deptOptions = this.deleteChildren(resp.data)
          _this.getparentData(_this.deptOptions)
        }
      })
    },
    getparentData(obj) {
      for (var i in obj) {
        this.rowDeptOptions.push(obj[i])
        if (obj[i].children) {
          this.getparentData(obj[i].children)
        }
      }
    },
    // 新增方法
    handleAdd() {
      var _this = this
      _this.emptySysDept()
      _this.editReadOnly = false
      _this.editShow = true
      _this.tableData = _this.tableData.slice(0, _this.total)
      // 获取选中行的deptID
      if (_this.multipleSelection.length === 1) {
        // for(rowDeptOptions)
        var InArray = _this.isInArray(_this.rowDeptOptions, _this.multipleSelection[0].deptId)
        if (InArray === false) {
          _this.msgInfo('该条数据下不能新增部门')
          return
        } else {
          _this.sysDept.parentId = _this.multipleSelection[0].deptId
          _this.handleGetDeptCode(_this.multipleSelection[0].deptId)
          var maxData = []
          if (_this.multipleSelection[0].children === null || _this.multipleSelection[0].children === undefined || _this.multipleSelection[0].children.length === 0) {
            _this.maxOrderNum = 0
          } else {
            for (var i in _this.multipleSelection[0].children) {
              maxData.push(_this.multipleSelection[0].children[i].orderNum)
            }
            _this.maxOrderNum = Math.max.apply(null, maxData)
          }
          if (_this.multipleSelection[0].deptType === '1' || _this.multipleSelection[0].deptType === '0') {
            this.deptSubCompanyTypeOptions = this.deptTypeOptions
          } else {
            this.deptSubCompanyTypeOptions = this.subCompanyTypeOptions
          }
        }
      } else {
        _this.maxOrderNum = _this.maxNum
      }
      _this.sysDept.orderNum = _this.maxOrderNum + 1
      console.log('maxOrderNum', _this.maxOrderNum, _this.maxOrderNum + 1)
      _this.dialogTitle = '新增部门'
      _this.dialogVisible = true
      _this.isParentIdDisabled = false
    },
    isInArray(arr, value) {
      for (var i = 0; i < arr.length; i++) {
        if (value === arr[i].id) {
          return true
        }
      }
      return false
    },
    selectParentId(node) {
      var parentId = node.id
      if (this.dialogTitle === '新增部门') {
        if (parentId !== '' && parentId != null && parentId !== undefined) {
          var deptId = parentId
          this.handleGetDeptCode(deptId)
        } else {
          this.sysDept.parentCode = ''
          this.sysDept.deptCode = ''
        }
      }
      this.sysDept.orderNum = node.orderNum
      // }
      if (node === null) {
        this.sysDept.orderNum = this.maxNum
      }
      this.sysDept.deptType = ''
      if (node.deptType === '1' || node.deptType === '0') {
        this.deptSubCompanyTypeOptions = this.deptTypeOptions
      } else {
        this.deptSubCompanyTypeOptions = this.subCompanyTypeOptions
      }
    },
    handleGetDeptCode(deptId) {
      console.log(deptId)
      // 查询父组件的本部门编码 赋值给页面的父部门编码
      getDeptCodeByParentCode({ 'deptId': deptId }).then(resp => {
        if (resp) {
          // 本页面的父部门编码 = 上级部门的本部门编码
          this.sysDept.parentCode = resp.data.deptCode
          // this.MaxDeptCode(this.sysDept.parentCode)
          this.sysDept.deptCode = resp.data.reserved1
        }
      })
    },
    intConvertString(num, length) {
      // 这里用slice和substr均可
      return (Array(length).join('0') + num).slice(-length)
    },
    // 获取本部门编码最大值
    MaxDeptCode(parentCode) {
      getDeptCodeByParentCode({ 'parentCode': parentCode }).then(res => {
        this.sysDept.deptCode = res
        // var a = this.maxDeptCode.length
        // var deptCode = parseInt(this.maxDeptCode) + 1
        // this.sysDept.deptCode = this.intConvertString(deptCode, a)
        // this.maxDeptCode = ''
      })
    },
    // 编辑操作
    handleUpdate() {
      this.editReadOnly = true
      this.editShow = false
      // 获取选中行的id
      var child = this.multipleSelection
      this.emptySysDept()
      this.isParentIdDisabled = true
      // 主键
      var id = child[0].deptId
      // 根据id查找这条的内容
      if (id === ' ' || id === null) {
        this.msgInfo('最顶级公司不能编辑')
      } else if (child[0].parentId === '0') {
        this.msgInfo('最顶级公司不能编辑')
      } else if (id === this.daptTreeDate[0].deptId) {
        this.msgInfo('最顶级公司不能编辑')
      } else {
        getDeptByDeptId(id)
          .then(resp => {
            if (resp) {
              var rowData = resp.data
              this.dialogTitle = '修改部门信息'
              this.deptSubCompanyTypeOptions = this.deptAndSubCompanyTypeOptions
              this.currentProvince = [rowData.province, rowData.city, rowData.county]
              this.sysDept.deptId = rowData.deptId
              this.sysDept.enterpriseId = rowData.enterpriseId
              this.sysDept.parentCode = rowData.parentCode
              this.sysDept.deptCode = rowData.deptCode
              this.sysDept.deptType = rowData.deptType
              this.sysDept.subCompany = rowData.subCompany
              if (rowData.parentId === '0') {
                this.sysDept.parentId = undefined
              } else {
                this.sysDept.parentId = rowData.parentId
              }
              this.sysDept.deptName = rowData.deptName
              this.sysDept.orderNum = rowData.orderNum
              this.sysDept.leader = rowData.leader
              this.sysDept.tempId = rowData.tempId
              this.sysDept.phone = rowData.phone
              this.sysDept.email = rowData.email
              this.sysDept.status = rowData.status
              this.sysDept.loginName = rowData.loginName
              this.sysDept.userName = rowData.userName
              this.sysDept.password = rowData.password
              this.dialogVisible = true
            } else {
              this.msgError(resp.message)
            }
          })
          .catch(() => {
          })
      }
    },
    // 弹框取消按钮
    cancel() {
      this.dialogVisible = false
      this.tableLoading = false
      this.editReadOnly = false
      this.editShow = true
      this.emptySysDept()
      // this.multipleSelection = []
      this.$refs.addSysDeptForm.resetFields()
    },
    // 弹框确认按钮
    submitForm(fromData) {
      var _this = this
      this.$refs[fromData].validate(valid => {
        console.log(valid)
        if (valid) {
          // if (_this.sysDept.deptType === '2') {
          //   _this.sysDept.loginName = ''
          //   _this.sysDept.userName = ''
          //   _this.sysDept.password = ''
          //   _this.sysDept.confirmPassword = ''
          // }
          if (_this.sysDept.loginName || _this.sysDept.userName || _this.sysDept.password) {
            if (!_this.sysDept.loginName) {
              _this.msgInfo('管理员账号不能为空')
              return
            } else if (_this.sysDept.loginName.length < 2 || _this.sysDept.loginName.length > 20) {
              _this.msgInfo('管理员账号长度不能小于2位，且不能大于20位')
              return
            } else if (!_this.sysDept.userName) {
              _this.msgInfo('管理员姓名不能为空')
              return
            } else if (_this.sysDept.userName.length < 2 || _this.sysDept.userName.length > 20) {
              _this.msgInfo('管理员姓名长度不能小于2位，且不能大于20位')
              return
            }
          }
          this.btnDisabled = true
          var deptId = this.sysDept.deptId
          if (deptId) {
            // 更新
            const sysDept = _this.sysDept
            updateDept(sysDept).then(resp => {
              if (resp) {
                _this.dialogVisible = false
                this.msgSuccess('修改成功!')
                this.multipleSelection = []
                _this.emptySysDept()
                _this.getList()
              } else {
                this.msgError(resp.message)
              }
              _this.btnDisabled = false
            })
          } else {
            if (_this.sysDept.loginName || _this.sysDept.userName || _this.sysDept.password) {
              if (!_this.sysDept.password) {
                _this.msgInfo('密码不能为空')
                this.btnDisabled = false
                return
              } else if (_this.sysDept.password.length < 2 || _this.sysDept.password.length > 20) {
                _this.msgInfo('密码长度不能小于6位，且不能大于20位')
                this.btnDisabled = false
                return
              }
            }
            if (_this.sysDept.password) {
              if (_this.sysDept.confirmPassword !== _this.sysDept.password) {
                _this.msgInfo('确认密码与登录密码不一致')
                this.btnDisabled = false
                return
              }
            }
            // 添加
            addDept(this.sysDept).then(resp => {
              if (resp) {
                _this.dialogVisible = false
                this.msgSuccess('新增成功!')
                _this.emptySysDept()
                this.multipleSelection = []
                _this.getList()
              } else {
                this.msgError(resp.message)
              }
              _this.btnDisabled = false
            })
          }
        } else {
          return false
        }
      })
      _this.editReadOnly = false
    },
    // 删除操作
    handleDelete() {
      var _this = this
      var child = this.multipleSelection

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var ids = ''
          for (var i = 0; i < child.length; i++) {
            ids += child[i].deptId + ','
          }
          // 去掉最后一个逗号
          if (ids.length > 0) {
            ids = ids.substr(0, ids.length - 1)
          }
          delDept(ids).then(resp => {
            if (resp) {
              this.msgSuccess('删除成功!')
              // 重新加载表格数据
              _this.getList()
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {
        })
    },
    // 分公司初始化
    initEntAdd() {
      // 获取选中行的id
      var child = this.multipleSelection
      this.emptySysDept()
      // 主键
      var enterpriseId = child[0].enterpriseId
      var deptName = child[0].deptName
      var subCompany = child[0].subCompany
      initialized(enterpriseId, subCompany).then(resp => {
        console.log(resp)
        if (resp) {
          const data = resp.data.Initialized
          if (data) {
            // 企业已经初始化
            this.detailVisible = true
            this.$nextTick(() => {
              this.$refs.initDetail.addFrom(enterpriseId, deptName, subCompany)
            })
            // this.$refs.initDetail.initalizeAdd(enterpriseId, subCompany)
          } else {
            this.addVisible = true
            this.$nextTick(() => {
              this.$refs.initAdd.addFrom(enterpriseId, deptName, subCompany)
            })
          }
        } else {
          return this.msgError(resp.message)
        }
      })
    },
    // 密码重置功能
    passwordReset() {
      this.$confirm('您确定要重置密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPswdSubCompany(this.multipleSelection[0].subCompany).then(resp => {
          if (resp) {
            this.msgSuccess('密码重置成功! 新密码为 111111')
          } else {
            this.msgError(resp.message)
          }
        })
        // this.initialize(this.multipleSelection[0].enterpriseId, this.multipleSelection[0].subCompany)
        // const userId = this.multipleSelection[0].userId
      })
        .catch(() => {
        })
    },
    // 启用禁用按钮代码
    handleStatusChange() {
      var _this = this
      const row = this.multipleSelection[0]
      const text = row.status === '0' ? '停用' : 's启用'
      this.$confirm('确认要' + text + '' + row.deptName + '用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          var status = row.status
          if (status === '0') {
            status = '1'
          } else {
            status = '0'
          }
          _this.sysDept.deptId = row.deptId
          _this.sysDept.enterpriseId = row.enterpriseId
          _this.sysDept.parentCode = row.parentCode
          _this.sysDept.deptCode = row.deptCode
          _this.sysDept.deptType = row.deptType
          _this.sysDept.parentId = row.parentId
          _this.sysDept.deptName = row.deptName
          _this.sysDept.orderNum = row.orderNum
          _this.sysDept.leader = row.leader
          _this.sysDept.phone = row.phone
          _this.sysDept.email = row.email
          _this.sysDept.status = status
          // _this.sysDept = row
          updateDept(_this.sysDept).then(resp => {
            if (resp) {
              this.msgSuccess('操作成功!')
              this.getList()
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {
        })
    },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    }

  }
}
</script>
<style scoped>
  /*.form-container {*/
  /*  padding: 0;*/
  /*}*/
</style>
